<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>TITLE</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/custom.form.css">
</head>
<body>
<div class="layui-form layuimini-form">
    <div class="layui-form-item">
        <div class="layui-input-inline">
            <input type="hidden" th:value="${id} " id="id" name="id" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">选择机器人</label>
        <div class="layui-input-block" id="robot_Id"></div>
    </div>


    <div class="layui-form-item">
        <label class="layui-form-label">选择群聊</label>
        <button class="layui-btn  layui-btn-normal " id="selectWeach" onclick="selectWeacht()" style="width: 100px;">
            请选择群聊
        </button>
        <button class="layui-btn layui-btn-primary" onclick="showSelect()" id="showGroundName"
                style="width: 150px;"></button>
        <!--        <div class="layui-input-inline" style="width:500px" id="wechatGroup_id"></div>-->
    </div>

    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">发送方式</label>
            <div class="layui-input-inline" style="width:500px">
                <input type="radio" name="sendType" value="1" title="立即发送" lay-filter="radio-sendType" checked>
                <input type="radio" name="sendType" value="0" title="选择日期" lay-filter="radio-sendType">
            </div>
        </div>
    </div>

    <div class="layui-form-item" id="timeShow">
        <div class="layui-inline">
            <label class="layui-form-label">选择日期</label>
            <div class="layui-input-inline">
                <input type="text" class="layui-input" id="time" placeholder="yyyy-MM-dd HH:mm:ss" name="time">
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">发送类型</label>
        <div class="layui-input-inline">
            <select name="fileType" lay-filter="select-fileType">

                <option value="1">文本</option>
                <option value="2">图片</option>
                <option value="3">视频</option>
                <option value="0">文件</option>
            </select>
        </div>
    </div>

    <!--上传图片 -->
    <div class="layui-form-item" id="imgShow">
        <label class="layui-form-label">上传图片</label>
        <div class="layui-input-inline" style="width:500px">
            <input type="hidden" name="imgs" class="multiple_show_img" value="">
            <button type="button" class="layui-btn layui-btn-primary" id="upload">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>
            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                预览：
                <div class="layui-upload-list" id="div-slide_show"></div>
            </blockquote>
        </div>
    </div>

    <!--上传视频 -->
    <div class="layui-form-item" id="videoShow">
        <label class="layui-form-label">上传视频</label>
        <div class="layui-input-inline" style="width:500px">
            <input type="hidden" name="videos" class="multiple_show_videos" value="">
            <button type="button" class="layui-btn layui-btn-primary" id="video">
                <i class="layui-icon">&#xe67c;</i>上传视频
            </button>
            <table class="layui-table">
                <thead>

                <th>文件名</th>
                <th>大小</th>
                <th>状态</th>
                <th>操作</th>

                </thead>
                <tbody id="videosList">
                <tr id="list">
                </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!--上传文件 -->
    <div class="layui-form-item" id="fileShow">
        <label class="layui-form-label">上传文件</label>
        <div class="layui-input-inline" style="width:500px">
            <input type="hidden" name="filesList" class="multiple_show_files" value="">
            <button type="button" class="layui-btn layui-btn-primary" id="file">
                <i class="layui-icon">&#xe67c;</i>上传文件
            </button>
            <table class="layui-table">
                <thead>
                <th>文件名</th>
                <th>大小</th>
                <th>状态</th>
                <th>操作</th>
                </thead>
                <tbody id="filesList">
                <tr id="fileList">
                </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!--文本类型 -->
    <div class="layui-form-item" id="textShow">
        <div class="layui-inline">
            <label class="layui-form-label">文本类型</label>
            <div class="layui-input-inline">
                <textarea name="text" style="width: 500px;height: 200px;" id="textType" placeholder="请输入文本"
                          class="layui-input"></textarea>

            </div>
        </div>
    </div>


    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" id="submitId" lay-submit lay-filter="submit">保存</button>
            <button class="layui-btn layui-btn-primary" onclick="cenCel()">关闭</button>
        </div>
    </div>
</div>
<script src="/layui/layui.all.js"></script>
<script src="/js/core.util.js"></script>
<script>
    var form = layui.form;
    var layer = layui.layer;
    var $ = jQuery = layui.jquery;
    var tree = layui.tree;
    var table = layui.table;
    var curIfr = parent.layer.getFrameIndex(window.name);
    var upload = layui.upload;
    var laydate = layui.laydate;
    //获取token
    var token = CoreUtil.getData("access_token");
    var tokenQuery = token.replace("#", "%23");
    var images = [];
    var videos = [];
    var filesList = [];
    var wechatGrounds = [];
    var wechatGroundName = [];
    var wechatGroundId = null;
    window.onload = function () {
        var id = $("#id").val()
        var robId, groupsId;
        if (!CoreUtil.isEmpty(id)) {
            CoreUtil.sendGet('/sendRecord/' + id, null, function (res) {
                if (res.data != null) {
                    robId = res.data.robotId
                    groupsId = res.data.wechatGroupId.split(',')
                    $("[name=fileType]").eq(0).find(`option[value=${res.data.fileType}]`).attr("selected", "true")
                    $("#time").val(res.data.sendTime)
                    reShow(res.data.fileType, res.data.fileUrl.split(','))
                    form.render('select')
                    console.log(res.data.fileType)
                    if (res.data.sendType == 1) {
                        $("#timeShow").hide();
                    }
                    wechatGrounds = res.data.wechatGroupId.split(",");
                    wechatGroundName = res.data.wechatGroupName.split(",");
                    $("#showGroundName").text("您已选择" + wechatGrounds.length + "个群聊");
                    $("#selectWeach").hide();
                    $("#submitId").hide();
                    $("#upload").hide();
                    $("#file").hide();
                    $("#video").hide();
                    $("#textType").attr("readOnly", true);
                }
            })
        } else {
            $("#imgShow").hide()
            $("#videoShow").hide()
            $("#fileShow").hide()
            $("#textShow").show()
            $("#timeShow").hide();
            $("#showGroundName").hide();
        }
        //选择机器人渲染
        CoreUtil.sendGet('/robot/list', null, function (res) {
            if (res.code === 0) {
                var str = $("#robot_Id").html();
                for (var i = 0; i < res.data.length; i++) {
                    str += `<input type="radio" name="robot" value="${res.data[i].id}" title="${res.data[i].name}" lay-filter="radio-type" checked="${robId == res.data[i].id}">`
                    wechatGroundId = res.data[i].id
                }
                $("#robot_Id").html(str)
                form.render("radio");
                // setTimeout(function () {
                //     CoreUtil.sendGet("/wechatGroup/findListByRobotId/" + robId, null, function (res1) {
                //         var str = $("#wechatGroup_id").html();
                //         for (var i = 0; i < res1.data.length; i++) {
                //             str += ` <input type="checkbox" value="${res1.data[i].id}" name="wechatGroup[]" title="${res1.data[i].groupName}" lay-filter="check-type">`
                //         }
                //         $("#wechatGroup_id").html(str)
                //         groupsId.forEach(id => {
                //             var inp = document.querySelector(`[value='${id}']`)
                //             $(inp).attr('checked', true)
                //         })
                //         form.render("checkbox");
                //     })
                // }, 300)
            }
        })
    }

    laydate.render({
        elem: '#time',//input的id
        type: 'datetime'//年月日，也是默认，不要这个也可以
    });

    function reShow(type, docName) {
        switch (type) {
            case 0:
                var filesView = $('#filesList');
                docName.forEach((name, index) => {
                    if (!name) return
                    var tr = $(['<tr id="fileList-' + index + '">',
                        '<td>' + name + '</td>',
                        '<td></td>',
                        '<td>上传成功</td>',
                        '<td>',
                        '<button class="layui-btn layui-btn-xs layui-btn-danger file-delete" disabled>删除</button>',
                        '</td>',
                        '</tr>'
                    ].join(''));
                    tr.on('click', function (e) {
                        if ($(e.target).hasClass('file-delete')) {
                            // delete files[index]; //删除对应的文件
                            filesList.splice($(this).index() - 1, 1);
                            tr.remove();
                            $('.multiple_show_files').val(filesList);
                        }
                    });
                    filesList.push(name);
                    $('.multiple_show_files').val(filesList);
                    filesView.append(tr);
                })
                $("#imgShow").hide()
                $("#videoShow").hide()
                $("#fileShow").show()
                $("#textShow").hide()
                break
            case 1:
                $('#textShow').find('textarea').eq(0).val(docName)
                $("#imgShow").hide()
                $("#videoShow").hide()
                $("#fileShow").hide()
                $("#textShow").show()
                break
            case 2:
                docName.forEach((name, index) => {
                    if (!name) return
                    $('#div-slide_show').append('<img src="' + name + '"  title="点击删除" class="layui-upload-img" style="width: 100px;height: 100px;" >&nbsp;')
                    //追加图片成功追加文件名至图片容器
                    images.push(name);
                    $('.multiple_show_img').val(images);
                })
                $("#imgShow").show()
                $("#videoShow").hide()
                $("#fileShow").hide()
                $("#textShow").hide()
                break
            case 3:
                var videosView = $('#videosList');
                docName.forEach((name, index) => {
                    if (!name) return
                    var tr = $(['<tr id="list-' + index + '">',
                        '<td>' + name + '</td>',
                        '<td></td>',
                        '<td>上传成功</td>',
                        '<td>',
                        '<button class="layui-btn layui-btn-xs layui-btn-danger video-delete">删除</button>',
                        '</td>',
                        '</tr>'
                    ].join(''));
                    tr.on('click', function (e) {
                        if ($(e.target).hasClass('video-delete')) {
                            console.log(videos, $(this).index())
                            // delete files[index]; //删除对应的文件
                            videos.splice($(this).index() - 1, 1);
                            tr.remove();
                            $('.multiple_show_videos').val(videos);
                        }
                    });
                    videos.push(res.data.src);
                    $('.multiple_show_videos').val(videos);
                    videosView.append(tr);
                    $("#imgShow").hide()
                    $("#videoShow").show()
                    $("#fileShow").hide()
                    $("#textShow").hide()
                })
        }
    }

    //上传图片
    upload.render({
        elem: '#upload'
        , url: '/sysFiles/upload?authorization=' + tokenQuery //上传接口
        , multiple: true
        , accept: "file"
        , exts: 'jpg|png|jpeg|gif'
        , done: function (res) {
            //如果上传成功
            if (res.code == 0) {
                $('#div-slide_show').append('<img src="' + res.data.src + '"  title="点击删除" class="layui-upload-img" style="width: 100px;height: 100px;" onclick="delMultipleImgs(this)">&nbsp;')
                //追加图片成功追加文件名至图片容器
                images.push(res.data.src);
                $('.multiple_show_img').val(images);
            } else {
                //提示信息
                layer.msg(res.msg);
            }
        }
    });

    function delMultipleImgs(this_img) {

        console.log(this_img)
        //获取下标
        var subscript = $("#div-slide_show img").index(this_img);
        //删除图片
        this_img.remove();
        //删除数组
        images.splice(subscript, 1);
        //重新排序
        images.sort();
        $('.multiple_show_img').val(images);
        //返回
        return;
    }

    //上传视频
    var videosView = $('#videosList'),
        uploadListIns = upload.render({
            elem: '#video'
            , url: '/sysFiles/oldUpload?authorization=' + tokenQuery //上传接口
            , multiple: true
            , size: '5120'
            , accept: "file"
            , exts: 'mp4|m4v|mp3|avi'
            , choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    console.log(index)
                    var tr = $(['<tr id="list-' + index + '">',
                        '<td>' + file.name + '</td>',
                        '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>',
                        '<td>等待上传</td>',
                        '<td>',
                        '<button class="layui-btn layui-btn-xs layui-btn-danger video-delete">删除</button>',
                        '</td>',
                        '</tr>'
                    ].join(''));
                    tr.on('click', function (e) {
                        if ($(e.target).hasClass('video-delete')) {
                            console.log(videos, $(this).index())
                            delete files[index]; //删除对应的文件
                            videos.splice($(this).index() - 1, 1);
                            tr.remove();
                            $('.multiple_show_videos').val(videos);
                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        }
                    });
                    videosView.append(tr);
                });
            },
            done: function (res, index, upload) {
                console.log(index)
                console.log(this.files)
                if (res.code == 0) { //上传成功
                    var tr = videosView.find('tr#list-' + index),
                        tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    videos.push(res.data.src);
                    $('.multiple_show_videos').val(videos);
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload, res.msg);
            },
            error: function (index, upload, msg) {
                var tr = videosView.find('tr#list-' + index),
                    tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">' + msg + '</span>');
            }
        });

    //上传文件
    var filesView = $('#filesList'),
        filesListIns = upload.render({
            elem: '#file'
            , url: '/sysFiles/oldUpload?authorization=' + tokenQuery //上传接口
            , multiple: true
            // ,size:'5120'
            , accept: 'file'
            , choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file) {
                    console.log(index)
                    var tr = $(['<tr id="fileList-' + index + '">',
                        '<td>' + file.name + '</td>',
                        '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>',
                        '<td>等待上传</td>',
                        '<td>',
                        '<button class="layui-btn layui-btn-xs layui-btn-danger file-delete">删除</button>',
                        '</td>',
                        '</tr>'
                    ].join(''));
                    tr.on('click', function (e) {
                        if ($(e.target).hasClass('file-delete')) {
                            delete files[index]; //删除对应的文件
                            filesList.splice($(this).index() - 1, 1);
                            tr.remove();
                            $('.multiple_show_files').val(filesList);
                            filesListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        }
                    });
                    filesView.append(tr);
                });
            },
            done: function (res, index, upload) {
                console.log(index)
                console.log(this.files)
                if (res.code == 0) { //上传成功
                    var tr = filesView.find('tr#fileList-' + index),
                        tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    filesList.push(res.data.src);
                    $('.multiple_show_files').val(filesList);
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload, res.msg);
            },
            error: function (index, upload, msg) {
                var tr = filesView.find('tr#fileList-' + index),
                    tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">' + msg + '</span>');
            }
        });

    //监听提交
    form.on('submit(submit)', function (data) {

        // for (var key in data.field) {
        //     if (key.includes('wechatGroup')) {
        //         arr.push(data.field[key])
        //     }
        // }
        var submitData = {
            fileUrl: '',
            robotId: '',
            wechatGroupId: '',
            sendType: '',
            sendTime: '',
            fileType: ''
        };
        switch (data.field.fileType) {
            case "0":
                submitData.fileType = 0;
                submitData.fileUrl = data.field.filesList;
                break;
            case "1":
                submitData.fileType = 1;
                submitData.fileUrl = data.field.text;
                break;
            case "2":
                submitData.fileType = 2;
                submitData.fileUrl = data.field.imgs;
                break;
            case "3":
                submitData.fileType = 3;
                submitData.fileUrl = data.field.videos;
                break;
        }


        if (data.field.sendType == 1) {
            submitData.sendType = 1;
        } else if (data.field.sendType == 0) {
            submitData.sendType = 0;
            submitData.sendTime = data.field.time
        }
        submitData.robotId = data.field.robot;
        submitData.wechatGroupId = wechatGrounds.join(',');
        if (submitData.wechatGroupId === null || submitData.wechatGroupId === undefined || submitData.wechatGroupId === "") {
            parent.layer.msg("请选择群聊");
            return false;
        }
        if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
            submitData.deleted = 1;
            CoreUtil.sendPost("/sendRecord/add", submitData, function (res) {
                if (res.code == 0) {
                    //跳出提示
                    parent.layer.msg(res.msg);
                    //刷新表格
                    setTimeout(function () {
                        parent.location.reload();
                    }, 1000)
                } else {
                    layer.msg(res.msg);
                }
            });
        } else {
            submitData.id = data.field.id;
            console.log(submitData)
            CoreUtil.sendPut("/sendRecord/update", submitData, function (res) {
                if (res.code == 0) {
                    //跳出提示
                    parent.layer.msg(res.msg);
                    //刷新表格
                    setTimeout(function () {
                        parent.location.reload();
                    }, 1000)
                } else {
                    layer.msg(res.msg);
                }
            });

        }
        return false;
    });

    function cenCel() {
        parent.layer.close(curIfr);
    }

    //监听菜单栏类型管理选项
    form.on('radio(radio-type)', function (data) {
        // $("#wechatGroup_id").html('')
        // CoreUtil.sendGet("/wechatGroup/findListByRobotId/" + data.value, null, function (res) {
        //     var str = $("#wechatGroup_id").html();
        //     for (var i = 0; i < res.data.length; i++) {
        //         str += ` <input type="checkbox" value="${res.data[i].id}" name="wechatGroup[]" title="${res.data[i].groupName}" lay-filter="check-type">`
        //     }
        //     $("#wechatGroup_id").html(str)
        //     form.render("checkbox");
        // })
        wechatGroundId = data.value;
    });

    // 选择表单的数据
    function selectWeacht() {
        if (wechatGroundId == null) {
            layer.msg("请先选择机器人")
        } else {
            var index = layer.open({
                title: '选择群聊',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['100%', '100%'],
                btn: ["确定", "取消"],
                content: '/index/selectWechat?id=' + wechatGroundId,
                yes: function (index) {
                    var res = window["layui-layer-iframe" + index].callbackdata()
                    if (res.length <= 0) {
                        layer.msg("请选择群聊")
                    } else {
                        wechatGrounds = res.arr;
                        wechatGroundName = res.name;
                        $("#showGroundName").text("您已选择" + wechatGroundName.length + "个群聊");
                        $("#showGroundName").show();
                        layer.close(index);
                    }
                }
            });
            $(window).on("resize", function () {
                layer.full(index);
            });
        }
    }

    function showSelect() {
        layer.msg("您选择的群聊是【" + wechatGroundName + "】");
    }

    //监听发送方式
    form.on('radio(radio-sendType)', function (data) {
        switch (data.value) {
            case "1":
                $("#timeShow").hide();
                break;
            case"0":
                $("#timeShow").show();
                break;


        }
        console.log(data)

    });

    //监听下拉框控件
    form.on('select(select-fileType)', function (data) {
        switch (data.value) {
            case '0':
                $("#imgShow").hide()
                $("#videoShow").hide()
                $("#fileShow").show()
                $("#textShow").hide()
                break;
            case '1':
                $("#imgShow").hide()
                $("#videoShow").hide()
                $("#fileShow").hide()
                $("#textShow").show()
                break;
            case '2':
                $("#imgShow").show()
                $("#videoShow").hide()
                $("#fileShow").hide()
                $("#textShow").hide()
                break;
            case '3':
                $("#imgShow").hide()
                $("#videoShow").show()
                $("#fileShow").hide()
                $("#textShow").hide()
                break;


        }
    })

</script>
</body>
</html>